﻿#ifndef WORKCONDITION_H
#define WORKCONDITION_H
#include <mutex>
#include <condition_variable>

#include <signalslot.h>

class EventLoop;

class REFLECTX_EXPORT WorkCondition
{
public:
    WorkCondition(unsigned int workCount = 0);

    void AddWork();
    void FinishWork();

	//等待任务结束
	//isAlive代表使用何种等待方式，false代表死等，线程卡在此处直到任务完成，true代表活等，在该处创建事件循环，在等待的同时能够处理事件
    void WaitForFinished(bool isAlive = false);

private:
    int m_workCount;
    std::recursive_mutex m_mutex;
    std::condition_variable_any m_con;
	std::set<EventLoop*> wait_loop;//处于等待中的事件队列
};

typedef std::shared_ptr<WorkCondition> WorkConditionPtr;

template<typename T>
class WorkFuture:public WorkCondition{
public:
    void FinishWork(T ret){
        this->ret = ret;
        WorkCondition::FinishWork();
    }

    T GetReturnValue() const{
        return ret;
    }

private:
    T ret;
};

class REFLECTX_EXPORT WorkConditionGurad{
public:
    WorkConditionGurad(WorkCondition& w);
    ~WorkConditionGurad();

private:
    WorkCondition& m_work;
};

#endif // WORKCONDITION_H
